<template>
  <div class="app-container">
    <el-header>
      <el-row class="flex flex-start main-child" justify="space-between">
        <div style="margin:10px 0; ;font-weight:bold;">
          <i class="iconfont icon-zuzhijiagou" /> 单位信息
        </div>
      </el-row>
      <el-row>
        <el-col style="text-align:right;" />
      </el-row>
    </el-header>
    <el-main>
      <el-card class="padding-bottom-sm" style="max-width:50vw">
        <el-row type="flex" justify="start" class="bg-grey light padding-sm margin-bottom-sm">
          <div>
            <span class="text-xl bold">{{ currUnit.UnitName }}</span>
          </div>
          <div class="margin-left">

            <el-button size="mini" type="primary" @click="handleChageCurrUnit">切换所在单位</el-button>
            <el-button v-if="currUnit.IsManager" size="mini" type="primary" plain @click="handleUpdate">编辑</el-button>
            <el-button size="mini" type="primary" plain @click="handleCreate">新建单位</el-button>
          </div>
        </el-row>

        <el-row class="padding-lr-sm padding-tb-sm">
          <el-col :span="22">
            <span class="bold">联系人：</span><span>{{ currUnit.Contact }}</span>
          </el-col>
        </el-row>
        <el-row class="padding-lr-sm padding-tb-sm">
          <el-col :span="22">
            <span class="bold">联系电话：</span><span>{{ currUnit.ContactPhone }}</span>
          </el-col>
        </el-row>
        <el-row class="padding-lr-sm padding-tb-sm">
          <el-col :span="22">
            <span class="bold">单位地址：</span><span>{{ currUnit.Address }}</span>
          </el-col>
        </el-row>
      </el-card>
    </el-main>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="add-unit">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-width="120px"
        style="width: 100%; "
      >
        <div class="split-row">
          <el-form-item label="单位名称" prop="UnitName" class="child">
            <el-input v-model="temp.UnitName" />
          </el-form-item>
          <el-form-item label="统一信用代码" prop="CreditCode" class="child">
            <el-input v-model="temp.CreditCode" />
          </el-form-item>
        </div>
        <div class="split-row">
          <el-form-item label="联系人" prop="Contact" class="child">
            <el-input v-model="temp.Contact" />
          </el-form-item>
          <el-form-item label="联系人电话" prop="ContactPhone" class="child">
            <el-input v-model="temp.ContactPhone" />
          </el-form-item>
        </div>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="省/市/区" class="child">
              <el-cascader
                v-model="temp.Area"
                :options="AreaData"
                :props="regionprops"
                style="width:100%;"
                @change="handleAreaChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="Address" class="child">
              <el-input v-model="temp.Address" placeholder="详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="短信签名">
          <el-input
            v-model="temp.SmsSign"
            type="text"
            placeholder="短信签名,最多10个字"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="短信预览">
          <div
            style="  padding: 10px;
                                  background: #ecf5ff;
                                  color: #409EFF;
                                  line-height: 18px;

                                  border-radius: 5px;"
          >【{{ temp.SmsSign }}】{{ "此内容为模拟短信内容" }}</div>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input
            v-model="temp.Remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button :loading="isLoading" type="primary" @click="dialogStatus==='create'?createData():updateData()">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择单位" :visible.sync="dialogChangeVisible" :before-close="handleClose">
      <el-card v-for="unit in units" :key="unit.Id" class="box-card padding" style="cursor:pointer">
        <div class="item text-bold" @click="chanageCurrUnit(unit.Id)">
          {{ unit.UnitName }}
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>
<script>
import { getCurrUnitInfo, addUnitInfo, editUnitInfo, GetMyAllUnits } from '@/api/unit/unit'
import { changeCurrUnit } from '@/api/user/user'
import { getRegionTree } from '@/api/region'
export default {
  filters: {},
  data() {
    return {
      AreaData: [],
      dialogFormVisible: false,
      dialogChangeVisible: false,
      dialogStatus: '',
      isLoading: false,
      currUnit: {},
      units: [],
      temp: {
        Id: '',
        Type: 2,
        UnitName: '',
        CreditCode: '',
        Address: '',
        Contact: '',
        ContactPhone: '',
        Province: '',
        City: '',
        Country: '',
        Area: '',
        SmsSign: '',
        Remark: ''
      },
      needWexinAccount: false,
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        UnitName: [
          { required: true, message: '单位名称必填', trigger: 'blur' },
          { max: 50, message: '单位名称不能超过50个字', trigger: 'blur' }
        ]
      },
      regionprops: {
        expandTrigger: 'hover',
        lazy: true,
        lazyLoad(node, resolve) {
          const nodes = node.children
          node.children = []
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes)
        }
      }
    }
  },
  created() {
    this.getUnitInfo()
    this.loadAreaData()
    this.getUserUnits()
  },
  methods: {
    loadAreaData() {
      getRegionTree().then(res => {
        this.AreaData = res.Data
      })
    },
    getUserUnits() {
      GetMyAllUnits().then(res => {
        this.units = res.Data
      })
    },
    getUnitInfo() {
      getCurrUnitInfo().then(response => {
        this.currUnit = response.Data
      })
    },
    handleAreaChange(value) {
      this.temp.Area = value
      this.temp.Province = value[0]
      this.temp.City = value[1]
      this.temp.Country = value[2]
    },
    resetTemp() {
      this.temp = {
        Id: '',
        Type: 2,
        UnitName: '',
        CreditCode: '',
        Address: '',
        Contact: '',
        ContactPhone: '',
        Province: '',
        City: '',
        Country: '',
        Area: '',
        SmsSign: '',
        Remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.isLoading = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          addUnitInfo(this.temp).then((res) => {
            this.$message({
              type: 'success',
              message: '新增成功',
              duration: 1000
            })
            this.dialogFormVisible = false
            this.resetTemp()
            this.getUserUnits()
            this.isLoading = false
            this.$confirm('现在是否切换到新单位？如果现在不切你可以到工作台的单位处切换.', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.chanageCurrUnit(res.Data.Id)
              })
          })
        } else {
          this.isLoading = false
        }
      })
    },
    handleUpdate() {
      this.temp = Object.assign({}, this.currUnit) // copy obj
      this.temp.Area = [this.temp.Province, this.temp.City, this.temp.Country]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.isLoading = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          editUnitInfo(tempData).then(() => {
            this.dialogFormVisible = false
            this.resetTemp()
            this.getUnitInfo()
            this.isLoading = false
          })
        } else {
          this.isLoading = false
        }
      })
      setTimeout(() => {
        this.isLoading = false
      }, 5000)
    },
    handleChageCurrUnit() {
      this.dialogChangeVisible = true
    },
    handleClose() {
      this.dialogChangeVisible = false
    },
    chanageCurrUnit(id) {
      this.handleClose()
      changeCurrUnit(id).then(res => {
        var _this = this
        _this.getUnitInfo()
        _this.$store.dispatch('user/getInfo').then(() => { // 拉取用户信息
          _this.$router.options.routes = _this.$router.options.resetRouter()
          _this.$store.dispatch('user/GetModulesTree').then(modules => { // 获取用户可访问的模块
            _this.$store.dispatch('GenerateRoutes', modules).then((newPaths) => { // 根据权限生成可访问的路由表
              const integralRoutes = newPaths.concat(_this.$router.options.routes)
              _this.$router.options.routes = integralRoutes
              _this.$router.addRoutes(newPaths) // 动态添加可访问路由表

              _this.$emit('reloadroute')
            })
          })
        }).catch(() => {
          _this.$store.dispatch('user/resetToken')
          _this.message.error('未能获取用户信息')
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.box-card:hover{
  background-color:#f1f1f1
}
</style>
